import logging

from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.erea.models import Area


class AreasView(View):
    def get(self, request):
        # 先从缓存中查找，
        provinces_list = cache.get('provinces')
        if provinces_list is None:  # 如果没有查到再进行数据库查询
            try:
                # 1查询所有的省
                provinces = Area.objects.filter(parent=None)
                # 2转换成字典
                provinces_list = []
                for province in provinces:
                    provinces_list.append({'id': province.id, 'name': province.name})
                cache.set('provinces', provinces_list, 3600 * 24)  # 设置缓存（key,value,time）
            except Exception:
                return JsonResponse({'code': 400, 'errmsg': '查询失败'})

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': provinces_list})


class SubAreaView(View):
    def get(self, request, id):
        sub_data = cache.get('subs_city_%s' % id)
        if sub_data is None:  # 如果没有查到再进行数据库查询
            try:
                parent_obj = Area.objects.get(id=id)
                sub_objs = parent_obj.subs.all()  # 获取二级的数据
                subs = []
                for sub in sub_objs:
                    subs.append({'id': sub.id, 'name': sub.name})
                sub_data = {'id': id, 'name': parent_obj.name, 'subs': subs}
                cache.set('subs_city_%s' % id, sub_data, 3600 * 24)  # 设置缓存（key,value,time）
            except Exception as e:
                logging.info('获取二级数据失败--{}'.format(e))
                return JsonResponse({'code': 400, 'errmsg': '二级数据查询失败'})
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': sub_data})
